//
//  registerViewController.m
//  FastRunDemo
//
//  Created by 苟亚明 on 16/10/17.
//  Copyright © 2016年 苟亚明. All rights reserved.
//

#import "registerViewController.h"
#import "registerNextViewController.h"
#import "loginTextField.h"
#import <AFNetworking.h>
#import "MBProgressHUD+MJ.h"
#import "SVProgressHUD.h"
NSString* const GYMNextSendCheckCodeDate = @"gymNextSendCheckCodeDate";

@interface registerViewController ()
@property (weak, nonatomic) IBOutlet UIButton *btnSendCode;
@property (weak, nonatomic) IBOutlet loginTextField *textNumber;
@property (weak, nonatomic) IBOutlet loginTextField *textCode;
/** 管理者 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

/**
 *  验证码发送间隔定时器。
 */
@property (nonatomic, strong) NSTimer* sendCheckCodeIntervalTimer;

/**
 *  验证码发送间隔定时器的重复次数。
 */
@property (nonatomic) NSInteger timerRepeatCount;
@end

@implementation registerViewController
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"注册";
}

- (void)viewWillAppear:(BOOL)animated {
    
    //  self.navigationController.navigationBarHidden=NO;
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSDate* nextSendCheckCodeDate = [userDefaults objectForKey:GYMNextSendCheckCodeDate];
    
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:nextSendCheckCodeDate];
    
    if (timeInterval < 0) {
        self.btnSendCode.enabled = NO;
        
        self.timerRepeatCount = -timeInterval;
        
        [self.sendCheckCodeIntervalTimer fire];
    }else {
        self.btnSendCode.enabled = YES;
    }
}
- (void)viewDidDisappear:(BOOL)animated {
    [self.sendCheckCodeIntervalTimer invalidate];
    
    self.sendCheckCodeIntervalTimer = nil;
}
- (IBAction)btnSendCodeClic:(id)sender {
    
    if (self.textNumber.text.length != 11) {
        [MBProgressHUD showError:@"输入手机号错误"];
        return;
    }
    
    
    // 发送短信请求
    NSString *url = [NSString stringWithFormat:@"%@%@%@/1",GYMRequeatHost,GYMSendCode,self.textNumber.text];
    
    [self.manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        
        
        NSLog(@"responseObject = %@",responseObject);
        if([responseObject[@"msg"] isEqualToString:@"该用户已注册"]){
            [MBProgressHUD showError:@"该用户已注册" toView:self.view];
            return;
        }
        [MBProgressHUD showSuccess:@"发送成功"];
        //禁止再次点击按钮。
        self.btnSendCode.enabled = NO;
        
        self.timerRepeatCount = 60;
        
        NSDate* nextSendCheckCodeDate = [NSDate dateWithTimeIntervalSinceNow:self.timerRepeatCount];
        
        //保存时间，下次进入该界面，如果不能发松，仍然显示倒计时。
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        
        [userDefaults setObject:nextSendCheckCodeDate forKey:GYMNextSendCheckCodeDate];
        
        [userDefaults synchronize];
        
        
        [self.sendCheckCodeIntervalTimer fire];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@" error = %@",error);
        [MBProgressHUD showError:@"发送失败"];
    }];
    
   

}

- (IBAction)btnNextStep:(id)sender {
//    if (self.textNumber.text.length == 11 && self.textCode.text.length != 0) {
    
        // 验证短信请求
        
        // 显示指示器
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        
        NSString *url = [NSString stringWithFormat:@"%@%@%@/1/%@",GYMRequeatHost,GYMCheckCode, self.textNumber.text,self.textCode.text];
        
        [self.manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
            
            NSString *result = responseObject[@"result"];
            
            [SVProgressHUD dismiss];
            
            NSLog(@"msg = %@",responseObject[@"msg"]);
//            if ([responseObject[@"msg"] isEqualToString:@"验证成功"]) {
                NSLog(@"验证成功");
                
                registerNextViewController *vc = [[registerNextViewController alloc]init];
                vc.telNumber = self.textNumber.text;
                vc.result = result;
                [self.navigationController pushViewController:vc animated:YES];
                return ;
//            }
            
//            [MBProgressHUD showError:@"验证失败"];
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"%@",error);
            [MBProgressHUD showError:@"验证失败"];
            [SVProgressHUD dismiss];
        }];
//    }
//    else{
//        [MBProgressHUD showError:@"输入不正确"];
//    }

    

}
- (void)changeSendCheckCodeButtonText:(NSTimer* )timer {
    self.timerRepeatCount--;
    
    [self.btnSendCode setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    
    if (self.timerRepeatCount > 0) {
        NSString* buttonTitle = [[NSString alloc] initWithFormat:@"%@S后重发", @(self.timerRepeatCount)];
        
        NSMutableAttributedString* buttonTitleAttributedTitle = [[NSMutableAttributedString alloc] initWithString:buttonTitle];
        NSInteger start = self.timerRepeatCount < 10 ? 2 : 3;
        [buttonTitleAttributedTitle addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, buttonTitle.length - 3)];
        [buttonTitleAttributedTitle addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(start, 3)];
        
        [self.btnSendCode setAttributedTitle:buttonTitleAttributedTitle forState:UIControlStateDisabled];
    }else {
        self.btnSendCode.enabled = YES;
        
        [self.btnSendCode setAttributedTitle:nil forState:UIControlStateDisabled];
        
        [self.sendCheckCodeIntervalTimer invalidate];
        
        self.sendCheckCodeIntervalTimer = nil;
    }
}
- (NSTimer* )sendCheckCodeIntervalTimer {
    if (_sendCheckCodeIntervalTimer == nil) {
        _sendCheckCodeIntervalTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(changeSendCheckCodeButtonText:) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:_sendCheckCodeIntervalTimer forMode:NSDefaultRunLoopMode];
    }
    
    return _sendCheckCodeIntervalTimer;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
